<?php

namespace app\admin\controller\user\extend;

use app\admin\model\agent\MoneyLog;
use app\admin\model\UserExtendMoneyLog;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Log;

/**
 * 推广员提现管理
 */
class Withdrawal extends Backend
{
    /**
     * Withdrawal模型对象
     * @var object
     * @phpstan-var \app\admin\model\user\extend\Withdrawal
     */
    protected object $model;

    protected string|array $defaultSortField = 'withdrawal_id,desc';

    protected array|string $preExcludeFields = ['create_time'];

    protected string|array $quickSearchField = ['withdrawal_id'];
    protected array $withJoinTable = ['user'];

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\user\extend\Withdrawal;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */


    /**
     * 设置已付款
     * @return void
     */
    public function payment (): void
    {
        $id = $this->request->get('id');
        $ret = $this->model->where('withdrawal_id', $id)->update(['status' => 1]);
        if (!$ret) {
            $this->error('设置失败');
        }
        $this->success('', $ret);
    }


    /**
     * 驳回提现
     * @return void
     */
    public function reject (): void
    {
        #开启事务
        Db::startTrans();
        try {
            $id = $this->request->get('id');
            $msg = $this->request->get('msg');
            $ret = $this->model->where('withdrawal_id', $id)->find();
            $ret->status = 2;
            $ret->msg = $msg;
            $ret->save();

            #将金额退回到推广员余额
            $user_id = $ret->user_id;
            $userInfo = \app\admin\model\User::where('id', $user_id)->find();
            $userInfo->extend_money = bcadd($userInfo->extend_money, $ret->price, 2);
            $userInfo->save();

            #记录到代理商余额变动表
            $userMoneyLog = new UserExtendMoneyLog();
            $userMoneyLogInfo = $userMoneyLog->where('user_id', $user_id)->order('create_time', 'desc')->find();
            $userMoneyLog->user_id = $user_id;
            $userMoneyLog->money = $ret->price;
            $userMoneyLog->before = $userMoneyLogInfo->after;
            $userMoneyLog->after = bcadd($userMoneyLogInfo->after, $ret->price, 2);
            $userMoneyLog->type = 1;
            $userMoneyLog->memo = '提现驳回 ' . $msg;
            $userMoneyLog->create_time = date('Y-m-d H:i:s', time());
            $userMoneyLog->save();
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error('提现驳回失败- ' . $e->getMessage());
            $this->error('驳回失败');
        }
        $this->success('驳回成功');
    }
}